<template>
  <div class="apple-select" :class="selectClass">
    <label v-if="label" class="apple-select__label" :for="inputId">
      {{ label }}
      <span v-if="required" class="apple-select__required">*</span>
    </label>
    
    <div
      class="apple-select__trigger"
      :class="triggerClass"
      @click="handleTriggerClick"
      @keydown="handleKeydown"
      :tabindex="disabled ? -1 : 0"
      :aria-expanded="visible"
      :aria-haspopup="true"
      role="combobox"
    >
      <div class="apple-select__content">
        <!-- 前缀图标 -->
        <span v-if="prefixIcon || $slots.prefix" class="apple-select__prefix">
          <slot name="prefix">
            <svg v-if="prefixIcon" class="apple-select__icon" viewBox="0 0 20 20" fill="currentColor">
              <use :href="`#icon-${prefixIcon}`"></use>
            </svg>
          </slot>
        </span>

        <!-- 选中值显示 -->
        <div class="apple-select__value" :class="valueClass">
          <template v-if="multiple && Array.isArray(selectedValues) && selectedValues.length > 0">
            <!-- 多选标签 -->
            <div class="apple-select__tags">
              <span
                v-for="value in displayValues"
                :key="value.value"
                class="apple-select__tag"
              >
                {{ value.label }}
                <button
                  v-if="!disabled"
                  class="apple-select__tag-close"
                  @click.stop="removeValue(value.value)"
                >
                  <svg viewBox="0 0 12 12" fill="currentColor">
                    <path d="M6 4.586L9.293 1.293a1 1 0 111.414 1.414L7.414 6l3.293 3.293a1 1 0 01-1.414 1.414L6 7.414l-3.293 3.293a1 1 0 01-1.414-1.414L4.586 6 1.293 2.707a1 1 0 011.414-1.414L6 4.586z"/>
                  </svg>
                </button>
              </span>
            </div>
          </template>
          <template v-else-if="!multiple && selectedLabel">
            <span class="apple-select__selected-text">{{ selectedLabel }}</span>
          </template>
          <template v-else>
            <span class="apple-select__placeholder">{{ placeholder }}</span>
          </template>
        </div>

        <!-- 清除按钮 -->
        <button
          v-if="clearable && hasValue && !disabled"
          class="apple-select__clear"
          @click.stop="handleClear"
          :aria-label="clearAriaLabel"
        >
          <svg viewBox="0 0 20 20" fill="currentColor">
            <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd" />
          </svg>
        </button>

        <!-- 下拉箭头 -->
        <span class="apple-select__arrow" :class="{ 'apple-select__arrow--open': visible }">
          <svg viewBox="0 0 20 20" fill="currentColor">
            <path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd" />
          </svg>
        </span>
      </div>
    </div>

    <!-- 下拉选项 -->
    <Teleport to="body">
      <Transition name="apple-select-dropdown">
        <div
          v-if="visible"
          ref="dropdown"
          class="apple-select__dropdown"
          :style="dropdownStyle"
        >
          <div class="apple-select__dropdown-content">
            <!-- 搜索框 -->
            <div v-if="filterable" class="apple-select__search">
              <AppleInput
                ref="searchInput"
                v-model="searchValue"
                placeholder="搜索选项..."
                prefix-icon="search"
                size="small"
              />
            </div>

            <!-- 选项列表 -->
            <div class="apple-select__options" :style="optionsStyle">
              <template v-if="filteredOptions.length > 0">
                <div
                  v-for="(option, index) in filteredOptions"
                  :key="option.value"
                  class="apple-select__option"
                  :class="getOptionClass(option, index)"
                  @click="handleOptionClick(option)"
                  @mouseenter="hoveredIndex = index"
                >
                  <slot name="option" :option="option" :index="index">
                    <!-- 多选复选框 -->
                    <input
                      v-if="multiple"
                      type="checkbox"
                      class="apple-select__option-checkbox"
                      :checked="isOptionSelected(option)"
                      @click.stop
                    />
                    
                    <!-- 选项标签 -->
                    <span class="apple-select__option-label">{{ option.label }}</span>
                    
                    <!-- 选中图标 -->
                    <span
                      v-if="!multiple && isOptionSelected(option)"
                      class="apple-select__option-check"
                    >
                      <svg viewBox="0 0 20 20" fill="currentColor">
                        <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
                      </svg>
                    </span>
                  </slot>
                </div>
              </template>
              
              <!-- 无选项 -->
              <div v-else class="apple-select__empty">
                <slot name="empty">
                  <span class="apple-select__empty-text">{{ emptyText }}</span>
                </slot>
              </div>
            </div>

            <!-- 加载状态 -->
            <div v-if="loading" class="apple-select__loading">
              <div class="apple-select__loading-spinner"></div>
              <span class="apple-select__loading-text">{{ loadingText }}</span>
            </div>
          </div>
        </div>
      </Transition>
    </Teleport>

    <!-- 帮助文本 -->
    <div v-if="helpText || errorMessage" class="apple-select__help">
      <span v-if="errorMessage" class="apple-select__error">{{ errorMessage }}</span>
      <span v-else-if="helpText" class="apple-select__help-text">{{ helpText }}</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch, nextTick, onMounted, onUnmounted } from 'vue'
import { createPopper } from '@popperjs/core'
import type { Instance as PopperInstance } from '@popperjs/core'
import AppleInput from './AppleInput.vue'

export interface SelectOption {
  label: string
  value: any
  disabled?: boolean
  group?: string
}

export interface AppleSelectProps {
  modelValue?: any
  options?: SelectOption[]
  placeholder?: string
  label?: string
  helpText?: string
  errorMessage?: string
  disabled?: boolean
  readonly?: boolean
  required?: boolean
  multiple?: boolean
  clearable?: boolean
  filterable?: boolean
  loading?: boolean
  size?: 'small' | 'medium' | 'large'
  variant?: 'default' | 'filled' | 'outlined'
  prefixIcon?: string
  maxHeight?: string | number
  emptyText?: string
  loadingText?: string
  clearAriaLabel?: string
  customClass?: string
}

const props = withDefaults(defineProps<AppleSelectProps>(), {
  options: () => [],
  placeholder: '请选择',
  disabled: false,
  readonly: false,
  required: false,
  multiple: false,
  clearable: false,
  filterable: false,
  loading: false,
  size: 'medium',
  variant: 'default',
  maxHeight: '240px',
  emptyText: '无选项',
  loadingText: '加载中...',
  clearAriaLabel: '清除选择',
  customClass: ''
})

const emit = defineEmits<{
  'update:modelValue': [value: any]
  'change': [value: any]
  'focus': []
  'blur': []
  'clear': []
  'visible-change': [visible: boolean]
}>()

// 内部状态
const visible = ref(false)
const searchValue = ref('')
const hoveredIndex = ref(-1)
const dropdown = ref<HTMLElement>()
const searchInput = ref()
const trigger = ref<HTMLElement>()
const popperInstance = ref<PopperInstance>()

// 计算属性
const inputId = computed(() => `apple-select-${Math.random().toString(36).substr(2, 9)}`)

const selectClass = computed(() => [
  `apple-select--${props.size}`,
  `apple-select--${props.variant}`,
  {
    'apple-select--disabled': props.disabled,
    'apple-select--readonly': props.readonly,
    'apple-select--error': props.errorMessage,
    'apple-select--multiple': props.multiple,
  },
  props.customClass
])

const triggerClass = computed(() => [
  'apple-select__trigger',
  {
    'apple-select__trigger--active': visible.value,
    'apple-select__trigger--disabled': props.disabled,
    'apple-select__trigger--readonly': props.readonly,
    'apple-select__trigger--error': props.errorMessage,
  }
])

const valueClass = computed(() => [
  {
    'apple-select__value--placeholder': !hasValue.value,
    'apple-select__value--multiple': props.multiple,
  }
])

const hasValue = computed(() => {
  if (props.multiple) {
    return Array.isArray(props.modelValue) && props.modelValue.length > 0
  }
  return props.modelValue !== null && props.modelValue !== undefined && props.modelValue !== ''
})

const selectedValues = computed(() => {
  if (!props.multiple) return []
  return Array.isArray(props.modelValue) ? props.modelValue : []
})

const selectedLabel = computed(() => {
  if (props.multiple) return ''
  const option = props.options.find(opt => opt.value === props.modelValue)
  return option?.label || ''
})

const displayValues = computed(() => {
  return selectedValues.value.map(value => {
    const option = props.options.find(opt => opt.value === value)
    return {
      value,
      label: option?.label || String(value)
    }
  })
})

const filteredOptions = computed(() => {
  if (!props.filterable || !searchValue.value) {
    return props.options.filter(option => !option.disabled)
  }
  
  const keyword = searchValue.value.toLowerCase()
  return props.options.filter(option => 
    !option.disabled && 
    option.label.toLowerCase().includes(keyword)
  )
})

const dropdownStyle = ref({})
const optionsStyle = computed(() => ({
  maxHeight: typeof props.maxHeight === 'number' ? `${props.maxHeight}px` : props.maxHeight
}))

// 工具函数
const isOptionSelected = (option: SelectOption) => {
  if (props.multiple) {
    return selectedValues.value.includes(option.value)
  }
  return props.modelValue === option.value
}

const getOptionClass = (option: SelectOption, index: number) => [
  {
    'apple-select__option--selected': isOptionSelected(option),
    'apple-select__option--disabled': option.disabled,
    'apple-select__option--hovered': hoveredIndex.value === index,
  }
]

// 事件处理
const handleTriggerClick = () => {
  if (props.disabled || props.readonly) return
  
  visible.value = !visible.value
  emit('visible-change', visible.value)
  
  if (visible.value) {
    emit('focus')
    nextTick(() => {
      updateDropdownPosition()
      if (props.filterable && searchInput.value) {
        searchInput.value.focus()
      }
    })
  } else {
    emit('blur')
  }
}

const handleOptionClick = (option: SelectOption) => {
  if (option.disabled) return
  
  if (props.multiple) {
    const values = [...selectedValues.value]
    const index = values.indexOf(option.value)
    
    if (index > -1) {
      values.splice(index, 1)
    } else {
      values.push(option.value)
    }
    
    emit('update:modelValue', values)
    emit('change', values)
  } else {
    emit('update:modelValue', option.value)
    emit('change', option.value)
    visible.value = false
    emit('visible-change', false)
  }
}

const removeValue = (value: any) => {
  if (props.disabled) return
  
  const values = selectedValues.value.filter(v => v !== value)
  emit('update:modelValue', values)
  emit('change', values)
}

const handleClear = () => {
  const newValue = props.multiple ? [] : ''
  emit('update:modelValue', newValue)
  emit('change', newValue)
  emit('clear')
}

const handleKeydown = (event: KeyboardEvent) => {
  if (props.disabled || props.readonly) return
  
  switch (event.key) {
    case 'Enter':
    case ' ':
      event.preventDefault()
      if (!visible.value) {
        handleTriggerClick()
      } else if (hoveredIndex.value >= 0 && hoveredIndex.value < filteredOptions.value.length) {
        handleOptionClick(filteredOptions.value[hoveredIndex.value])
      }
      break
    case 'Escape':
      if (visible.value) {
        visible.value = false
        emit('visible-change', false)
      }
      break
    case 'ArrowDown':
      event.preventDefault()
      if (!visible.value) {
        handleTriggerClick()
      } else {
        hoveredIndex.value = Math.min(hoveredIndex.value + 1, filteredOptions.value.length - 1)
      }
      break
    case 'ArrowUp':
      event.preventDefault()
      if (visible.value) {
        hoveredIndex.value = Math.max(hoveredIndex.value - 1, 0)
      }
      break
  }
}

const updateDropdownPosition = () => {
  if (!dropdown.value || !trigger.value) return
  
  if (popperInstance.value) {
    popperInstance.value.destroy()
  }
  
  popperInstance.value = createPopper(trigger.value, dropdown.value, {
    placement: 'bottom-start',
    strategy: 'fixed',
    modifiers: [
      {
        name: 'offset',
        options: {
          offset: [0, 8],
        },
      },
      {
        name: 'preventOverflow',
        options: {
          padding: 16,
        },
      },
      {
        name: 'flip',
        options: {
          fallbackPlacements: ['top-start', 'bottom-end', 'top-end'],
        },
      },
    ],
  })
}

const handleClickOutside = (event: Event) => {
  const target = event.target as Node
  if (dropdown.value && !dropdown.value.contains(target) && 
      trigger.value && !trigger.value.contains(target)) {
    visible.value = false
    emit('visible-change', false)
  }
}

// 生命周期
onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
  if (popperInstance.value) {
    popperInstance.value.destroy()
  }
})

// 监听器
watch(visible, (newVisible) => {
  if (newVisible) {
    searchValue.value = ''
    hoveredIndex.value = -1
  }
})

watch(filteredOptions, () => {
  hoveredIndex.value = -1
})
</script>

<style lang="scss" scoped>
.apple-select {
  position: relative;
  width: 100%;

  &--small {
    font-size: 14px;
  }

  &--medium {
    font-size: 16px;
  }

  &--large {
    font-size: 18px;
  }
}

.apple-select__label {
  display: block;
  font-size: 14px;
  font-weight: 500;
  color: var(--apple-color-text-primary);
  margin-bottom: 6px;
}

.apple-select__required {
  color: var(--apple-color-error);
  margin-left: 2px;
}

.apple-select__trigger {
  display: flex;
  align-items: center;
  width: 100%;
  min-height: 44px;
  padding: 0 16px;
  background: var(--apple-color-background-primary);
  border: 1px solid var(--apple-color-separator);
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  outline: none;

  &:hover:not(&--disabled):not(&--readonly) {
    border-color: var(--apple-color-accent);
  }

  &--active {
    border-color: var(--apple-color-accent);
    box-shadow: 0 0 0 3px var(--apple-color-accent-alpha-low);
  }

  &--disabled {
    background: var(--apple-color-background-tertiary);
    color: var(--apple-color-text-quaternary);
    cursor: not-allowed;
  }

  &--readonly {
    cursor: default;
  }

  &--error {
    border-color: var(--apple-color-error);

    &:hover,
    &.apple-select__trigger--active {
      border-color: var(--apple-color-error);
      box-shadow: 0 0 0 3px var(--apple-color-error-alpha-low);
    }
  }

  .apple-select--small & {
    min-height: 36px;
    padding: 0 12px;
  }

  .apple-select--large & {
    min-height: 52px;
    padding: 0 20px;
  }
}

.apple-select__content {
  display: flex;
  align-items: center;
  width: 100%;
  gap: 8px;
}

.apple-select__prefix {
  display: flex;
  align-items: center;
  color: var(--apple-color-text-tertiary);
}

.apple-select__icon {
  width: 16px;
  height: 16px;
}

.apple-select__value {
  flex: 1;
  display: flex;
  align-items: center;
  min-height: 20px;
  
  &--placeholder .apple-select__placeholder {
    color: var(--apple-color-text-quaternary);
  }
}

.apple-select__tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  width: 100%;
}

.apple-select__tag {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 2px 8px;
  background: var(--apple-color-accent-alpha-low);
  color: var(--apple-color-accent);
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.apple-select__tag-close {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 14px;
  height: 14px;
  border: none;
  background: none;
  color: currentColor;
  cursor: pointer;
  border-radius: 2px;
  transition: background-color 0.2s ease;

  &:hover {
    background: var(--apple-color-accent-alpha-medium);
  }

  svg {
    width: 8px;
    height: 8px;
  }
}

.apple-select__selected-text,
.apple-select__placeholder {
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.apple-select__clear {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
  border: none;
  background: none;
  color: var(--apple-color-text-tertiary);
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.2s ease;

  &:hover {
    background: var(--apple-color-background-secondary);
    color: var(--apple-color-text-secondary);
  }

  svg {
    width: 16px;
    height: 16px;
  }
}

.apple-select__arrow {
  display: flex;
  align-items: center;
  color: var(--apple-color-text-tertiary);
  transition: transform 0.2s ease;

  &--open {
    transform: rotate(180deg);
  }

  svg {
    width: 16px;
    height: 16px;
  }
}

.apple-select__dropdown {
  position: absolute;
  z-index: 9999;
  min-width: 200px;
  background: var(--apple-color-background-primary);
  border: 1px solid var(--apple-color-separator);
  border-radius: 8px;
  box-shadow: 
    0 10px 25px -3px rgba(0, 0, 0, 0.1),
    0 4px 6px -2px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.apple-select__dropdown-content {
  padding: 4px 0;
}

.apple-select__search {
  padding: 8px 12px;
  border-bottom: 1px solid var(--apple-color-separator);
  margin-bottom: 4px;
}

.apple-select__options {
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-track {
    background: transparent;
  }

  &::-webkit-scrollbar-thumb {
    background: var(--apple-color-separator);
    border-radius: 3px;
  }
}

.apple-select__option {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  cursor: pointer;
  transition: background-color 0.2s ease;

  &:hover,
  &--hovered {
    background: var(--apple-color-background-secondary);
  }

  &--selected {
    background: var(--apple-color-accent-alpha-low);
    color: var(--apple-color-accent);
  }

  &--disabled {
    color: var(--apple-color-text-quaternary);
    cursor: not-allowed;
  }
}

.apple-select__option-checkbox {
  width: 16px;
  height: 16px;
  margin: 0;
}

.apple-select__option-label {
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.apple-select__option-check {
  width: 16px;
  height: 16px;
  color: var(--apple-color-accent);
}

.apple-select__empty,
.apple-select__loading {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 24px 16px;
  color: var(--apple-color-text-tertiary);
  font-size: 14px;
}

.apple-select__loading {
  gap: 8px;
}

.apple-select__loading-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid var(--apple-color-separator);
  border-top: 2px solid var(--apple-color-accent);
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.apple-select__help {
  margin-top: 6px;
  font-size: 12px;
  line-height: 1.4;
}

.apple-select__error {
  color: var(--apple-color-error);
}

.apple-select__help-text {
  color: var(--apple-color-text-tertiary);
}

// 下拉动画
.apple-select-dropdown-enter-active,
.apple-select-dropdown-leave-active {
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}

.apple-select-dropdown-enter-from,
.apple-select-dropdown-leave-to {
  opacity: 0;
  transform: translateY(-8px) scale(0.95);
}

// 暗色模式
@media (prefers-color-scheme: dark) {
  .apple-select__dropdown {
    box-shadow: 
      0 10px 25px -3px rgba(0, 0, 0, 0.4),
      0 4px 6px -2px rgba(0, 0, 0, 0.2);
  }
}

// 高对比度模式
@media (prefers-contrast: high) {
  .apple-select__trigger {
    border-width: 2px;
  }

  .apple-select__dropdown {
    border-width: 2px;
  }
}

// 减少动画模式
@media (prefers-reduced-motion: reduce) {
  .apple-select__trigger,
  .apple-select__arrow,
  .apple-select__option {
    transition: none;
  }

  .apple-select-dropdown-enter-active,
  .apple-select-dropdown-leave-active {
    transition: opacity 0.1s;
  }

  .apple-select__loading-spinner {
    animation: none;
  }
}
</style>